#include <stdio.h> 
#include <stdlib.h>
#include "esp_common.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
#include "espressif/espconn.h"
#include "user_config.h"
#include "cJSON/cJSON.h"
#include "mfs.h"
#include "webserver.h"



static int8_t ICACHE_FLASH_ATTR
get_systeminfo(int client){
	cJSON* jsRet = NULL;
	uint32_t len;
	char *buf,*retStr;
	uint8_t bssid[6];
	struct station_config sta_conf;
	struct softap_config config;

	jsRet = cJSON_CreateObject();
	if(NULL == jsRet){
		free(buf);
		return -1;
	}
	cJSON_AddStringToObject(jsRet,"ver","1.0.0");
	cJSON_AddStringToObject(jsRet,"macid","112233445566");

	retStr = cJSON_PrintUnformatted(jsRet);
	cJSON_Delete(jsRet);
	http_head(client,strlen(retStr));
	STRSEND(client,retStr);
	//os_printf("send:%s\n",retStr);
	free(retStr);
	
	return 0;
}


const php_funcationType php_fun[]={
	{"status.php", 10, get_systeminfo},
	{NULL,0,not_found},
};




static int8_t ICACHE_FLASH_ATTR
set_wifisystem(int client,webConn *conn){
	char *buf = NULL;
	int len;
	cJSON *Json = NULL,*s,*p,*a,*c;
	buf = (char *)malloc(conn->postLen + 1);
	if(buf == NULL)
		goto out; 
	len = read(client,buf,conn->postLen);
	if(len != conn->postLen){
		goto out;
	}
	buf[len] = '\0';
	//os_printf("rev:%s\n",buf);

	Json = cJSON_Parse(buf);
	if(Json == NULL)
		goto out;
	a = cJSON_GetObjectItem(Json,"apname");
	c = cJSON_GetObjectItem(Json,"apkey");
	s = cJSON_GetObjectItem(Json,"staname");
	p = cJSON_GetObjectItem(Json,"stakey");
	if(a && c && s && p){
		wifi_set_opmode_current(STATIONAP_MODE);
		http_head(client,strlen("OK"));
		STRSEND(client,"OK");
		vTaskDelay(200);
		//wifi_sta_change(s->value.valuestring,p->value.valuestring);
		//wifi_ap_change(a->value.valuestring,c->value.valuestring);
		stop_webserver();

	}
out:
	if(buf) free(buf);
	if(Json) cJSON_Delete(Json);
	return 0;
}



const php_funPostType post_php_fun[]={
	{"set.php", 7, set_wifisystem},
	{NULL,0,post_not_found},
};